import axios from 'axios'
import qs from 'qs'
import Vue from 'vue'
import router from '@/router'

const createConfig = { baseURL: process.env.VUE_APP_BASE_API, timeout: 25000 }
const getCookieMessage = (params, config) => params.forEach(value => (config.data[value] = Vue.prototype.$cookie.get(value)))
const instance = axios.create(createConfig)
/**
 * @description 请求参数处理函数
 * @param {Object} requestObj
 */
function requestSuccessFunc(requestObj) {
  if (['post', 'put', 'delete'].includes(requestObj.method)) {
    if (requestObj.url !== 'elise/login') getCookieMessage(['token'], requestObj)
    requestObj.data = qs.stringify(requestObj.data)
  } else {
    requestObj.params['token'] = Vue.prototype.$cookie.get('token')
  }
  return requestObj
}

function requestFailFunc(requestError) {
  return Promise.reject(requestError)
}
/**
 * @description 响应成功处理函数
 * @param {Object} responseObj
 */
function responseSuccessFunc(responseObj) {
  const { data: body } = responseObj
  if (body.respCode === '101') {
    Vue.prototype.$Notice.warning({ desc: body.respMsg })
    location.reload()
    sessionStorage.clear()
    Vue.prototype.$cookie.remove('token')
    return Promise.reject(responseObj)
  } else if (body.respCode === '801') {
    Vue.prototype.$Notice.error({ desc: body.respMsg })
    return Promise.reject(responseObj)
  } else if (!['200', '100', '208','207'].includes(body.respCode)) {
    Vue.prototype.$Message.error(body.respMsg)
    return Promise.reject(responseObj)
  }
  return responseObj
}
/**
 * @description 响应失败处理函数
 * @param {Object} responseError
 */
function responseFailFunc(responseError) {
  const { response: res } = responseError
  switch (res.status) {
    case 403:
      router.push('/403')
      break
    case 404:
      router.push('/404')
      break
    case 500:
      router.push('/500')
      break
  }
  return Promise.reject(responseError)
}

instance.interceptors.request.use(requestSuccessFunc, requestFailFunc)
instance.interceptors.response.use(responseSuccessFunc, responseFailFunc)

const createAPI = (url, method, config = {}) => instance({ url, method, ...config })
export default createAPI
